from datetime import datetime

from flask import json
from exts import db
from models.user import AdminUser, RoleType
from models.warehouse import Inventory, AuditRecord, AuditStatus, InventoryStatus
from models.user import AdminUser, RoleType
from services.user_service import *
from services.warehouse_service import *
from services.item_service import *
from services.inventory_service import *



class audit_service:
    def get_all_inventories(self):
        """获取所有库存信息"""
        inventories = Inventory.query.all()
        return [
            {
                "id": inventory.id,
                "warehouse_id": inventory.warehouse_id,
                "warehouse_name": warehouse_service().get_id_warehouse(inventory.warehouse_id)['name'],
                "item_id": inventory.item_id,
                "item_name": item_service().get_item_by_id(inventory.item_id)['name'],
                "quantity": inventory.quantity,
                "status": inventory.status.name,
                "created_by": inventory.created_by,
                "created_at": inventory.created_at.isoformat(),
            }
            for inventory in inventories
        ]

    def get_inventory(self, inventory_id):
        """获取单个库存信息"""
        if not inventory_id:
            raise Exception("库存ID不能为空")
        inventory = Inventory.query.get(inventory_id)
        if not inventory:
            raise Exception("库存记录不存在")
        return {
            "id": inventory.id,
            "warehouse_id": inventory.warehouse_id,
            "warehouse_name": warehouse_service().get_id_warehouse(inventory.warehouse_id)['name'],
            "item_id": inventory.item_id,
            "item_name": item_service().get_item_by_id(inventory.item_id)['name'],
            "quantity": inventory.quantity,
            "status": inventory.status.name,
            "created_by": inventory.created_by,
            "created_at": inventory.created_at.isoformat(),
        }

    def get_audit_records(self, user_id, role_type):
        """获取所有审计记录"""
        if role_type == RoleType.SUPER:
            # 超级管理员获取所有审��记录
            audit_records = AuditRecord.query.all()
        elif role_type == RoleType.AUDIT:
            # 审计管理员获取自己的审计记录
            audit_records = AuditRecord.query.filter_by(auditor_id=user_id).all()
        else:
            raise Exception("无权限获取审计记录")

        return [
            {
                "id": record.id,
                "inventory_id": record.inventory_id,
                "auditor_id": record.auditor_id,
                "auditor_name": user_service().get_user_info(record.auditor_id)['username'],
                "status": record.status.value,
                "comment": record.comment,
                "created_at": record.created_at.isoformat(),
            }
            for record in audit_records
        ]

    def get_audit_record(self, audit_record_id, user_id, role_type):
        """获取单条审计记录"""
        audit_record = AuditRecord.query.get(audit_record_id)
        if not audit_record:
            raise Exception("审计记录不存在")

        if role_type == RoleType.AUDIT and audit_record.auditor_id != user_id:
            raise Exception("无权限查看此审计记录")

        return {
            "id": audit_record.id,
            "inventory_id": audit_record.inventory_id,
            "auditor_id": audit_record.auditor_id,
            "auditor_name": user_service().get_user_info(audit_record.auditor_id)['username'],
            "status": audit_record.status.name,
            "comment": audit_record.comment,
            "created_at": audit_record.created_at.isoformat(),
        }

    def update_inventory_audit(self, inventory_id, user_id, role_type, status, comment):
        """更新库存审核状态并创建审计记录"""
        if role_type not in [RoleType.SUPER, RoleType.AUDIT]:
            raise Exception("无权限进行审核操作")
        if not inventory_id:
            raise Exception("库存ID不能为空")
        if not status:
            raise Exception("审核状态不能为空")

        # 检查该库存是否已有审计记录
        existing_audit = AuditRecord.query.filter_by(inventory_id=inventory_id).first()
        if existing_audit:
            raise Exception(f"库存记录 {inventory_id} 已被审查，不能再次审查")

        try:
            # 验证审计状态
            audit_status = AuditStatus(status)
            # 验证库存状态
            inventory_status = InventoryStatus(status)
        except ValueError:
            valid_audit_status = [sta.value for sta in AuditStatus]
            valid_inventory_status = [sta.value for sta in InventoryStatus]
            raise Exception(
                f"无效的状态 {status}，有效的审计状态为 {valid_audit_status}，有效的库存状态为 {valid_inventory_status}"
            )

        inventory = Inventory.query.get(inventory_id)
        if not inventory:
            raise Exception("库存记录不存在")

        # 更新库存状态
        inventory.status = inventory_status
        new_audit_record = AuditRecord(
            inventory_id=inventory_id,
            auditor_id=user_id,  # 使用用户 ID 作为审核人 ID
            status=audit_status,
            comment=comment,
        )
        db.session.add(new_audit_record)
        db.session.commit()
        return {
            "inventory_id": inventory.id,
            "new_status": inventory.status.name,
            "audit_record_id": new_audit_record.id,
        }

    def update_audit_record(self, audit_record_id, user_id, role_type, status, comment):
        """修改审计记录，更新库存状态并新增一条审计信息"""
        if role_type not in [RoleType.SUPER, RoleType.AUDIT]:
            raise Exception("无权限进行修改审计记录操作")
        if not audit_record_id:
            raise Exception("审计记录ID不能为空")
        if not status:
            raise Exception("审核状态不能为空")

        # 获取旧的审计记录
        old_audit_record = AuditRecord.query.get(audit_record_id)
        if not old_audit_record:
            raise Exception("审计记录不存在")

        if role_type == RoleType.AUDIT and old_audit_record.auditor_id != user_id:
            raise Exception("无权限修改此审计记录")

        try:
            # 验证审计状态
            audit_status = AuditStatus(status)
            # 验证库存状态
            inventory_status = InventoryStatus(status)
        except ValueError:
            valid_audit_status = [sta.value for sta in AuditStatus]
            valid_inventory_status = [sta.value for sta in InventoryStatus]
            raise Exception(
                f"无效的状态 {status}，有效的审计状态为 {valid_audit_status}，有效的库存状态为 {valid_inventory_status}"
            )

        # 获取对应的库存记录
        inventory = Inventory.query.get(old_audit_record.inventory_id)
        if not inventory:
            raise Exception("库存记录不存在")

        # 更新库存状态
        inventory.status = inventory_status

        # 新增一条审计记录
        new_audit_record = AuditRecord(
            inventory_id=old_audit_record.inventory_id,
            auditor_id=user_id,  # 使用用户 ID 作为审核人 ID
            status=audit_status,
            comment=comment,
        )
        db.session.add(new_audit_record)
        db.session.commit()

        return {
            "inventory_id": inventory.id,
            "new_status": inventory.status.name,
            "new_audit_record_id": new_audit_record.id,
        }

    def delete_audit_record(self, audit_record_id, role_type):
        """删除审计记录"""
        if role_type != RoleType.SUPER:
            raise Exception("只有超级管理员可以删除审计记录")

        audit_record = AuditRecord.query.get(audit_record_id)
        audit_info = audit_record
        if not audit_record:
            raise Exception("审计记录不存在")

        db.session.delete(audit_record)
        db.session.commit()
        return {
            "message": "审计记录删除成功",
            "deleted_audit_record_id": {
                "id": audit_info.id,
                "inventory_id": audit_info.inventory_id,
                "auditor_id": audit_info.auditor_id,
                "status": audit_info.status.name,
                "comment": audit_info.comment,
                "created_at": audit_info.created_at.isoformat(),
            },
        }
